#include <unistd.h>
#include "xianshi.h"

#include <QLabel>
#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QPainter>  
#include <QMouseEvent>  
#include <QPropertyAnimation>
#include <QSequentialAnimationGroup>
#include <QPushButton>
#include <QTimeLine>

namespace han_zi{
hanzi::~hanzi()
{
        lines.clear();
        strokeid=0;
   // this->close();
    //this->deleteLater();
}
hanzi::hanzi(QWidget* parent,HandWriteRecognizer::Character* pcharacter)
     :QWidget(parent){  

    setMinimumSize(this->size());
    setMaximumSize(this->size());
    this->setMouseTracking(true);  
    this->isPressed = false;  
    this->isBox=false;
    this->isDispStr=false;
    isLine=false;
    mycharacter=pcharacter;
    strokeid=0;
    if(pcharacter!=NULL)
        strokeid=mycharacter->strokeCount;
    //printf("%s",mycharacter->word.c_str());
}  

void hanzi::paintCharacter(QSize q_size){
    if(mycharacter==NULL) return ;
    //printf("%d,%d",q_size.width(),q_size.height());

    QPainter painter(this);  
    QPen pen;                                 //创建一个画笔  
    pen.setColor(Qt::darkCyan);  
    pen.setWidth(3);
    pen.setStyle(Qt::SolidLine);
    pen.setCapStyle(Qt::RoundCap);
    pen.setJoinStyle(Qt::RoundJoin);
    painter.setPen(pen);  

  float xw=mycharacter->width/q_size.width();
    float yh=mycharacter->height/q_size.height();
   // printf("%f,%f;",xw,yh);

    for(int i=0;i<mycharacter->strokeCount;i++){
    HandWriteRecognizer::Stroke *tmpStroke=&(mycharacter->strokes[i]);
    
    //printf("笔画%d,w:%f,h:%f;",i+1,xw,yh);

    for(int j=0;j<tmpStroke->points.size()-1;j++)
    {
        myLine* sline = new myLine;  //put the new line into vector  
        sline->startPnt.setX(tmpStroke->points[j].x/xw);  
        sline->startPnt.setY(tmpStroke->points[j].y/yh);  
        sline->endPnt.setX(tmpStroke->points[j+1].x/xw);  
        sline->endPnt.setY(tmpStroke->points[j+1].y/yh); 
        painter.drawLine(sline->startPnt,sline->endPnt); 
        //printf("x,y(%d,%d);",sline->startPnt.x(),sline->startPnt.y());

    }        
 //sleep(1);
    }
       //printf("\t%s\n",tmpCharacter->word.c_str());

}
void hanzi::paintBox(){
    QPainter painter(this);
    QPen pen;
    pen.setBrush(QBrush(Qt::darkGray));//设置笔刷，你可以不用设置
    QVector<qreal> dashes;
    qreal space = 3;
    dashes << 5 << space << 5 <<space;
    pen.setDashPattern(dashes);
    pen.setWidth(1);
    painter.setPen(pen);
    int w=this->size().width()-1;
    int h=this->size().height()-1;
    painter.drawRect(0,0,w,h);
    painter.drawLine(0,0,w,h);
    painter.drawLine(w,0,0,h);
    painter.drawLine(w/2,0,w/2,h);
    painter.drawLine(0,h/2,w,h/2);
}
void hanzi::paintStr(){
    if(mycharacter==NULL) return ;
    QPainter painter(this);
    string dispstr=mycharacter->word.c_str();
    if(dispstr.size()<1) return;

    // 设置画笔颜色
    if(mycharacter->bUser)
        painter.setPen(QColor(0, 0, 0));
    else
        painter.setPen(Qt::red);
        QTextOption option(Qt::AlignRight |Qt::AlignBottom);
        option.setWrapMode(QTextOption::WordWrap);
        QFontMetrics fm = painter.fontMetrics();
         QString strText = mycharacter->word.c_str();
            QString strElidedText = fm.elidedText(strText, Qt::ElideRight, 200, Qt::TextShowMnemonic);
        painter.drawText(this->rect(),strElidedText,option);

}
/*笔顺动画*/
void hanzi::hzAnimation(){
          if(mycharacter==NULL) return ;
        float xw=mycharacter->width/this->size().width();
          float yh=mycharacter->height/this->size().height();

          QSequentialAnimationGroup* bhgroup=new QSequentialAnimationGroup(this);
          //bird_1->show();

            QList<QLabel *> bird;
          for(int i=0;i<mycharacter->strokeCount;i++){
          HandWriteRecognizer::Stroke *tmpStroke=&(mycharacter->strokes[i]);
          if(tmpStroke->points.size()>0){
              QLabel *pLabel = new QLabel(this);
             pLabel->resize(64,64);

              QPixmap birdimg=QPixmap(":/game/prefix1/bi.png").scaled(64,64,Qt::KeepAspectRatio);

              /*
               * QPixmap *birdimg=new QPixmap(30,30);
              QPainter painter(birdimg);
              painter.setPen(Qt::red);
              painter.setBrush(QBrush(Qt::red)); //设置画刷形式
                painter.drawEllipse(0,0,29,29);//画圆
              //birdimg->fill(Qt::transparent);
                */
             pLabel->setPixmap(birdimg);

             if(i!=0)
               pLabel->hide();
             else
                 pLabel->show();
             // pLabel->move(-100,-100);
              bird.append(pLabel);

          QPropertyAnimation *anim1=new QPropertyAnimation(bird.at(i), "pos");
             anim1->setDuration(2000);
              anim1->setStartValue(QPoint(tmpStroke->points[0].x/xw,(tmpStroke->points[0].y/yh-64)));
              int j=0;
          for( j=0;j<tmpStroke->points.size()-1;++j)
          {
              double f=(double)1.0/tmpStroke->points.size()*j;
                 anim1->setKeyValueAt(f,QPoint(tmpStroke->points[j].x/xw,(tmpStroke->points[j].y/yh-64)));

          }
          anim1->setEndValue(QPoint(tmpStroke->points[j].x/xw,(tmpStroke->points[j].y/yh-64)));
            //anim1->setCurveShape(QTimeLine::LinearCurve);

          bhgroup->addAnimation(anim1);

            connect(anim1,SIGNAL(finished()),this,SLOT(onfinished()));// 连接信号槽


          }

          }
          // 连接信号槽
              connect(bhgroup, SIGNAL(currentAnimationChanged(QAbstractAnimation*)),
                      this, SLOT(onCurrentAnimationChanged(QAbstractAnimation* )));

          bhgroup->start();

}
void hanzi::hzAnimation2(){
          if(mycharacter==NULL) return ;
          if(mycharacter->strokeCount>0){

        float xw=mycharacter->width/this->size().width();
          float yh=mycharacter->height/this->size().height();




            this->lines.clear();

          for(int i=0;i<mycharacter->strokeCount;i++){
          HandWriteRecognizer::Stroke *tmpStroke=&(mycharacter->strokes[i]);
          if(tmpStroke->points.size()>0){
              int j=0;
          for( j=1;j<tmpStroke->points.size();++j)
          {
              startPnt = QPoint(tmpStroke->points[j-1].x/xw,(tmpStroke->points[j-1].y/yh));
              endPnt = QPoint(tmpStroke->points[j].x/xw,(tmpStroke->points[j].y/yh));
              myLine* line = new myLine;  //put the new line into vector
              line->startPnt = startPnt;
              line->endPnt = endPnt;
              this->lines.push_back(line);
          }

          }

          }
          int s=lines.size();
          if(s>0){
          // 构造帧范围为 0 - 100，持续时间为 1000 毫秒（1 秒）的 timeline
          QTimeLine *timeLine = new QTimeLine(1000*s, this);
          timeLine->setFrameRange(0, 100*s);
          connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(onframeChanged(int)));
          timeLine->start();
          }
}

}
void hanzi::onframeChanged(int frame)
{


    int s=0;
    if(lines.size()>0)
    {
        time_frame=frame;
        update();

    }


}

void hanzi::onfinished()
{

    QPropertyAnimation *pAnimation = dynamic_cast<QPropertyAnimation *>(sender());
    if (pAnimation == NULL)
        return;

    QLabel *pLabel = dynamic_cast<QLabel *>(pAnimation->targetObject());//获得当前所操控的动画对象
    if (pLabel != NULL){
        pLabel->move(-100,-100);
        delete pLabel;
    }
    //printf("finished");
}

// 动画切换时会调用
void hanzi::onCurrentAnimationChanged(QAbstractAnimation *current)
{

    QPropertyAnimation *pAnimation = dynamic_cast<QPropertyAnimation *>(current);

    if (pAnimation == NULL)
        return;

    QLabel *pLabel = dynamic_cast<QLabel *>(pAnimation->targetObject());//获得当前所操控的动画对象
    if (pLabel != NULL)
        pLabel->show();
        //pLabel->move(-100,-100);

}
void hanzi::paintLine()
{
    QPainter painter(this);
    QPen pen;                                 //创建一个画笔
    pen.setColor(Qt::darkCyan);
    pen.setWidth(7);
    pen.setStyle(Qt::SolidLine);
    pen.setCapStyle(Qt::RoundCap);
    pen.setJoinStyle(Qt::RoundJoin);
    painter.setPen(pen);

    for(int i = 0;i<lines.size();i++){
        myLine* pLine = lines[i];
        painter.drawLine(pLine->startPnt,pLine->endPnt);
    }
}

//画线的0.f
void hanzi::bhLine(QColor color)
{
    QPainter painter(this);
    QPen pen;                                 //创建一个画笔
    pen.setColor(color);
    pen.setStyle(Qt::SolidLine);
    pen.setCapStyle(Qt::RoundCap);
    pen.setJoinStyle(Qt::RoundJoin);
    pen.setWidth(7);
    painter.setPen(pen);
    for(int i = 0;i<lines.size();i++){
        myLine* pLine = lines[i];
        int s=time_frame/100;
        float f=(float)(time_frame%100)/100;
        if(s==i)
        {
            QPoint t;
            int x;
            int y;
            x=(pLine->endPnt.x()-pLine->startPnt.x())*f+pLine->startPnt.x();
            y=(pLine->endPnt.y()-pLine->startPnt.y())*f+pLine->startPnt.y();

            t.setX(x);
            t.setY(y);
            painter.drawLine(pLine->startPnt,t);
            break;
        }
        painter.drawLine(pLine->startPnt,pLine->endPnt);
    }


}

void hanzi::paintEvent(QPaintEvent*p){

    if(isBox)
    paintBox();
  if(isLine){
    paintLine();
  }
  else{
    QSize s=this->size();
    //printf("%d,%d\n",s.width(),s.height());
    paintCharacter(s);
    }
    if(isDispStr)
    paintStr();
    bhLine(Qt::red);
}  
  
void hanzi::mousePressEvent(QMouseEvent *e){
    if(isLine){
    setCursor(Qt::PointingHandCursor);  
    startPnt = e->pos();  
    endPnt = e->pos();  

    this->isPressed = true;  
    if(mycharacter!=NULL){
        mycharacter->addPoint(strokeid,e->pos().x(),e->pos().y());

    }
    }
}  
  
void hanzi::mouseMoveEvent(QMouseEvent *e){
    if(this->isPressed){  
        endPnt = e->pos();  
        if(mycharacter!=NULL){
            mycharacter->addPoint(strokeid,e->pos().x(),e->pos().y());
        }
        myLine* line = new myLine;  //put the new line into vector  
        line->startPnt = startPnt;  
        line->endPnt = endPnt;  
        this->lines.push_back(line);  
  
        update();                                    //repainter，call paintEvent  
        startPnt = endPnt;  
    }  
}  
  
void hanzi::mouseReleaseEvent(QMouseEvent *e){
    setCursor(Qt::ArrowCursor);  
    this->isPressed = false;  
    if(mycharacter!=NULL){
        mycharacter->addPoint(strokeid,e->pos().x(),e->pos().y());
        strokeid++;
    }
}  
}
#include "xianshi.moc"
